<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    button.back-top {
      position: fixed;
      bottom: 50px;
      right: 50px;
    }
    .showHide{
      position: fixed;
      top: 50px;
      left: 100px;
    }
  </style>
</head>

<body style="height: 3000px">
  <div id="app">
    <button @click="isShow=!isShow" class="showHide">{{isShow?'隐藏':'显示'}}</button>
    <button v-if="isShow" class="back-top" v-backtop="200">回到顶部</button>
  </div>
  <script src="./vue.js"></script>
  <script>
    Vue.directive('backtop',{
      inserted(el,binding) {
        //  默认元素隐藏
        el.style.display = "none";
        // 添加全局滚动事件
        window.onscroll = function() {
          const sTop = document.documentElement.scrollTop || document.body.scrollTop;
          console.log(sTop);
          if (sTop > binding.value) {
            el.style.display = "block";
          } else {
            el.style.display = "none";
          }
        }
        // 给按钮添加点击事件 点击回到顶部
        el.onclick = function() {
          window.scrollTo(0,0);
        }
      },
      unbind(){
        console.log('解绑');
        window.onscroll = null;
      }
    })
    const vm = new Vue({
      el: '#app',
      data: {
        isShow: true
      }
    })
  </script>
</body>

</html>